<template>
  <div>
    <button @click="setEditable(false)">禁用</button>
    <button @click="setEditable(true)">启用</button>
    <div ref="divRef" style="height: 600px">
      <div class="aie-container">
        <div class="aie-container-header"></div>
        <div class="content">
          <div style='width: 200px;border-right: 1px solid #e5e7eb'>
            <div class="menuTitle">标题目录</div>
            <div class="titleContent">
              <div v-for='(item,index) in titles'
                   class="titleItem ellipsis"
                   :title="item.text"
                   :style="{paddingLeft:`${(item.level - 1) * 20}px`}"
                   @click="goFocus(item.pos,item.size)">
                {{item.text}}
              </div>
            </div>
          </div>
          <div class="aie-container-main"></div>
        </div>
        <div class="aie-container-footer"></div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import {AiEditor} from "aieditor";
import "aieditor/dist/style.css"

import {onMounted, onUnmounted, ref} from "vue";

const divRef = ref();
let aiEditor: AiEditor | null = null;
const titles = ref([])

onMounted(() => {
  aiEditor = new AiEditor({
    element: divRef.value as Element,
    placeholder: "点击输入内容...",
    content: '',
    htmlPasteConfig: {
      pasteAsText: true,
      pasteClean: true,
      removeEmptyParagraphs: true,
      pasteProcessor: (html) => {
        console.log(html,'复制内容');
        return html;
      }
    },
    fontFamily:{
      values:[
        {name: "宋体", value: "SimSun"},
        {name: "仿宋", value: "FangSong"},
        {name: "黑体", value: "SimHei"},
        {name: "楷体", value: "KaiTi"},
        {name: "微软雅黑", value: "Microsoft YaHei"},
      ]
    },
    fontSize:{
      defaultValue: 18,
    },
    toolbarKeys: ["undo", "redo", "brush", "eraser",
      "|", "heading", "font-family", "font-size",
      "|", "bold", "italic", "underline", "strike",
      "|","subscript", "superscript", "hr",
      "|", "highlight", "font-color",
      "|", "align", "line-height",
      "|", "bullet-list", "ordered-list", "indent-decrease", "indent-increase", "break",
      "|", "image", "quote", "table",
      "|", "fullscreen", {
        icon: "<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 24 24\" fill=\"currentColor\"><path d=\"M6.9998 6V3C6.9998 2.44772 7.44752 2 7.9998 2H19.9998C20.5521 2 20.9998 2.44772 20.9998 3V17C20.9998 17.5523 20.5521 18 19.9998 18H16.9998V20.9991C16.9998 21.5519 16.5499 22 15.993 22H4.00666C3.45059 22 3 21.5554 3 20.9991L3.0026 7.00087C3.0027 6.44811 3.45264 6 4.00942 6H6.9998ZM5.00242 8L5.00019 20H14.9998V8H5.00242ZM8.9998 6H16.9998V16H18.9998V4H8.9998V6Z\"></path></svg>",
        onClick: (event, editor) => {
          //点击事件
          copyToClipboard(editor.getHtml())
        },
        tip: "全文复制",
      },
    ],
    textSelectionBubbleMenu: {
      enable: true,
      items: ["ai", "Bold", "Italic", {
        id: "comment",
        title: "评论",
        icon: "<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 24 24\" fill=\"currentColor\"><path d=\"M7.29117 20.8242L2 22L3.17581 16.7088C2.42544 15.3056 2 13.7025 2 12C2 6.47715 6.47715 2 12 2C17.5228 2 22 6.47715 22 12C22 17.5228 17.5228 22 12 22C10.2975 22 8.6944 21.5746 7.29117 20.8242ZM7.58075 18.711L8.23428 19.0605C9.38248 19.6745 10.6655 20 12 20C16.4183 20 20 16.4183 20 12C20 7.58172 16.4183 4 12 4C7.58172 4 4 7.58172 4 12C4 13.3345 4.32549 14.6175 4.93949 15.7657L5.28896 16.4192L4.63416 19.3658L7.58075 18.711Z\"></path></svg>",
        onClick: (editor) => {
          const text = prompt('请输入要添加的批注内容：');
          const textEle = editor.getHtml() // 获取编辑器的内容 DOM 元素
          const selection = editor.getSelectedText(); // 获取当前选中的文本
          // 创建一个新的 span 元素来包裹选中的文本
          const span = document.createElement('span');
          span.style.backgroundColor = 'yellow';
          span.style.border = '1px solid red';
          span.textContent = selection;
          span.title = text
          console.log(selection,span.outerHTML, textEle);
          console.log(textEle.replace(selection, span.outerHTML),45444)

          editor.setContent(textEle.replace(selection, span.outerHTML))
        }
      }],
    },
    onChange:(editor)=>{
      // 监听到用编辑器内容发生变化了，控制台打印编辑器的 html 内容...
      console.log(editor.getHtml())
      getLines()
      titles.value = editor.getOutline() as []
    },
    onSave:(editor: AiEditor)=>{
      //通过这里进行保存的逻辑操作
      console.log('保存成功')
      return true
    }
  })
})

const goFocus = (pos:number,size:number):void => {
  aiEditor?.focusPos(pos+size-1)
}
const copyToClipboard = (text:string) => {
  navigator.clipboard.writeText(text)
      .then(function() {
        console.log('Text copied to clipboard');
      })
      .catch(function(err) {
        console.error('Failed to copy text: ', err);
      });
}
const setEditable = (flag:boolean) => {
  aiEditor?.setEditable(flag)
}
const getLines = () => {
  let content = aiEditor?.getHtml() as string; // 获取 HTML 内容
  let lines = 0
  const container = document.createElement('div');
  container.innerHTML = content;
  const children = container.children;
  for (let i = 0; i < children.length; i++) {
    const child = children[i];
    const content = child.textContent ?? "";
    const styleString = child.getAttribute('style') || '';
    let offset: number = 0
    if(styleString){
      styleString.split(';').forEach((v,i)=>{
        if(v.split(':')[0] === 'text-indent'){
          offset = Number(v.split(':')[1].replace('em',''))
        }
      })
    }
    const totalNum = content.length + offset
    if ( totalNum < 44){
      lines++
    }else {
      lines += Math.ceil(totalNum/ 44);
    }
    console.log(lines,i)
  }
  console.log("行数: ",lines);
}

onUnmounted(() => {
  aiEditor && aiEditor.destroy();
})
</script>
<style lang="scss" scoped>
.content {
  height: calc(100% - 60px);
  display: flex;
  .menuTitle {
    margin-top: 10px;
    height: 20px;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  .titleContent {
    height: calc(100% - 30px);
    box-sizing: border-box;
    padding: 5px;
    overflow: auto;
    .titleItem {
      box-sizing: border-box;
      padding: 5px;
    }
     .ellipsis {
       white-space: nowrap; /* 防止文本换行 */
       overflow: hidden; /* 隐藏溢出的内容 */
       text-overflow: ellipsis; /* 显示省略号来代表被修剪的文本 */
     }
    .titleItem:hover {
      cursor: pointer;
      background: #f9f9f9;
    }
  }
  .aie-container-main {
    //height: 100%;
    width: 820px;
    margin: 0 auto;
    overflow: auto;
    background: #f9f9f9;
  }
  :deep(.aie-content) {
    font-size: 18px;
    text-align: left;
    font-family: 'SimSun';
  }
}
</style>